package com.example.demo.controller;

import com.example.demo.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@Slf4j
@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {

    @Value("${img.path}")
    private String imgPath;

    @RequestMapping("/sayhi")
    public String sayHi(){
        return "hello h1";
    }

    //采用Post
    @RequestMapping(method = RequestMethod.POST, value = "/sayhi2")
    public String sayHi2(){
        return "hello h2";
    }

    @GetMapping("/sayhi3")
    public String sayHi3(){
        return "hello h3";
    }

    @PostMapping("/sayhi4")
    public String sayHi4(){
        return "hello h4";
    }

    //传单个参数
    @RequestMapping("/getuserbyid")
    public UserInfo getUserById(Integer id) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setUsername("张三");
        userInfo.setAge(18);
        return userInfo;
    }

    //传多个参数
    @RequestMapping("/login")
    public String login(@RequestParam(value = "name", required = false) String username,
                        String password) {
        return "用户名：" + username + " | 密码：" + password;
    }

    //传对象
    @RequestMapping("/reg")
    public String reg(UserInfo userInfo) {
        return "用户信息：" + userInfo;
    }

    //传JSON对象
    @RequestMapping("/reg2")
    public String reg2(@RequestBody UserInfo userInfo) {
        return "用户信息：" + userInfo;
    }

    //获取URL中的参数
    @RequestMapping("/hero/{id}/{name}")
    public String getHeroInfo(@PathVariable Integer id, @PathVariable String name){
        return "ID: "+id + " | Name: " + name;
    }

    //上传文件
    @RequestMapping("/upload")
    public boolean uploadPic(// @RequestPart参数是上传的文件名
            Integer uid, @RequestPart("img")MultipartFile file){
        boolean result = false;
        // 获取文件名(包括后缀)
        String fileName = file.getOriginalFilename();
        // 拿到后缀
        fileName = fileName.substring(fileName.lastIndexOf("."));
        //随机文件名并加上后缀
        fileName = UUID.randomUUID().toString() + fileName;
        try {
            //将文件保存到指定路径
            file.transferTo(new File(imgPath + fileName));
            result = true;
        } catch (IOException e) {
            log.error("上传图片失败" + e.getMessage());
        }
        return result;
    }

    //获取cookie
    @RequestMapping("/cookie")
    public void getCookie(HttpServletRequest request){
        //得到全部的cookie
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies){
            log.info("Cookie Name:" + cookie.getName() +
                    " | Cookie Value:" + cookie.getValue());
        }
    }
    @RequestMapping("/cookie2")
    public String getCookie2(@CookieValue("tmp") String cookie){
        return "Cookie Value: " + cookie;
    }

    //获取Header(请求头的信息)
    @RequestMapping("/gethead")
    public String getHead(HttpServletRequest request){
        return "header:" + request.getHeader("User-Agent");
    }
    @RequestMapping("/gethead2")
    public String getHead2(@RequestHeader("User-Agent") String userAgent){
        return "header:" + userAgent;
    }

    //存储session
    @RequestMapping("/setsess")
    public boolean setSession(HttpServletRequest request) {
        boolean result = false;
        // 1.得到 HttpSession
        HttpSession session = request.getSession(true); // true=如果没有会话，那么创建一个会话
        // 2.使用 setAtt 设置值
        session.setAttribute("userinfo", "张三");
        result = true;
        return result;
    }

    //获取session
    @RequestMapping("/getsess")
    public String getSession(HttpServletRequest request) {
        String result = null;
        // 1.得到 HttpSession 对象
        // false=如果有会话，使用会话，如果没有，那么不会新创建会话
        HttpSession session = request.getSession(false);
        // 2.getAtt 得到 Session 信息
        if (session != null && session.getAttribute("userinfo") != null) {
            result = (String) session.getAttribute("userinfo");
        }
        return result;
    }
    @RequestMapping("/getsess2")
    public String getSession2(@SessionAttribute(value = "userinfo",
            required = false) String userinfo) {
        //这里要添加一个required = false, 表示没有其他参数, 否则报错
        return "会话：" + userinfo;
    }

    //前端传递参数
    @RequestMapping("/login2")
    public HashMap<String, Object> login2(String username, String password){
        HashMap<String, Object> result = new HashMap<>();
        int state = 200; // 状态码
        int data = -1; // 等于1就登录成功
        String msg = "登录成功!";
        if (StringUtils.hasLength(username) && StringUtils.hasLength(password)){// 这个方法用来判空
            if (username.equals("admin") && password.equals("admin")){
                data = 1;
            }else {
                msg = "用户名或者密码错误!";
            }
        }else {
            msg = "非法参数!";
        }
        result.put("state", state);
        result.put("data" , data);
        result.put("msg", msg);
        return result;
    }

    //前端传递JSON
    @RequestMapping("/login3")
    public HashMap<String, Object> login3(@RequestBody UserInfo userInfo){
        HashMap<String, Object> result = new HashMap<>();
        int state = 200; // 状态码
        int data = -1; // 等于1就登录成功
        String msg = "登录成功!";
        if (StringUtils.hasLength(userInfo.getUsername())
                && StringUtils.hasLength(userInfo.getPassword())){// 这个方法用来判空
            if (userInfo.getUsername().equals("admin") && userInfo.getPassword().equals("admin")){
                data = 1;
            }else {
                msg = "用户名或者密码错误!";
            }
        }else {
            msg = "非法参数!";
        }
        result.put("state", state);
        result.put("data" , data);
        result.put("msg", msg);
        return result;
    }
}
